package com.anysoft.user;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.ClearSignFingerprintConfirmBean;
import com.anysoft.bean.OpenSignFingerprintApplyBean;
import com.anysoft.bean.OpenSignFingerprintConfirmBean;
import com.anysoft.bean.UserBean;
import com.anysoft.event.GestureEvent;
import com.anysoft.login.SetGestureStep1Activity;
import com.anysoft.me.callback.StringDialogCallback;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.PreferencesUtils;
import com.anysoft.utils.RSACryptographyUtil;
import com.anysoft.view.dialog.IcbcDialog;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wwq on 2017/1/23.
 */

public class PasswordManageActivity extends BaseActivity {

    private static final int ERROR_TIEMS = 3;

    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.titlebar)
    FrameLayout titlebar;
    @BindView(R.id.iv_change_pwd)
    ImageView ivChangePwd;
    @BindView(R.id.rl_change_pwd)
    RelativeLayout rlChangePwd;
    @BindView(R.id.sb_gesture_pwd)
    SwitchButton sbGesturePwd;
    @BindView(R.id.iv_change_gesture_pwd)
    ImageView ivChangeGesturePwd;
    @BindView(R.id.rl_change_gesture_pwd)
    RelativeLayout rlChangeGesturePwd;
    @BindView(R.id.sb_finger_print_pwd)
    SwitchButton sbFingerPrintPwd;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.rl_finger_print)
    RelativeLayout rlFingerPrint;

    private boolean isGestureChanged = true;
    private boolean isFingerPrintChanged = true;

    private FingerprintManager manager;//访问指纹硬件的类
    private KeyguardManager keyManager;//管理锁屏的类
    private CancellationSignal signal;
    //此类基于Java加密API的一个包装类,用于防止在指纹扫描中被第三方恶意攻击
    private FingerprintManager.CryptoObject cryptoObject;

//    private int fingerErrorNum = 0; // 指纹错误次数

    private IcbcDialog fingerPrintDialog;
    private String passwordStr;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_password_manage);
        ButterKnife.bind(this);

        title.setText("密码管理");

        CheckViewState();

        sbGesturePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //System.out.println("isChecked-----" + isChecked + ",isGestureChanged-----" + isGestureChanged);
                if (isChecked) {
                    isRecordIdentNumber(1, isChecked);
//                    if (isGestureChanged) {
//                        showInputDialog(1, isChecked, false);
//                    } else {
//                        isGestureChanged = true;
//                    }
                } else {
                    if (isGestureChanged) {
                        clearPwd(2);
                    } else {
                        isGestureChanged = true;
                    }
                }
            }
        });

        sbFingerPrintPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isRecordIdentNumber(2, isChecked);
//                    if (isFingerPrintChanged) {
//                        showInputDialog(2, isChecked, false);
//                    } else {
//                        isFingerPrintChanged = true;
//                    }
                } else {
                    if (isFingerPrintChanged) {
                        clearPwd(1);
                    } else {
                        isFingerPrintChanged = true;
                    }
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 清空手势或指纹密码
     *
     * @param type 1指纹  2手势
     */
    private void clearPwd(final int type) {
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        params.put("loginState", type + "");

        Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.CLEAR_SIGN_FINGER_PRINT_CONFIRM, params));
        OkGo.<String>post(HostConstant.CLEAR_SIGN_FINGER_PRINT_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateClear(response.body(), type);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateClear(String json, int type) {
        ClearSignFingerprintConfirmBean bean;
        try {
            bean = new Gson().fromJson(json, ClearSignFingerprintConfirmBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            clearFail(type);
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            clearFail(type);
            return;
        }

        switch (type) {
            case 1:
                clearFingerPrint(mentorApplication.userBean.getUserId());
                break;
            case 2:
                PreferencesUtils.putBoolean(this, findUserId() + "CanGesture", true);
                clearGesture(mentorApplication.userBean.getUserId());

                rlChangeGesturePwd.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void clearFail(int type) {
        switch (type) {
            case 1:
                isGestureChanged = false;
                sbGesturePwd.setChecked(true);
                break;
            case 2:
                isFingerPrintChanged = false;
                sbFingerPrintPwd.setChecked(true);
                break;
            default:
                break;
        }
    }

    /**
     * 显示输入密码弹框
     *
     * @param type      1--手势密码，2--指纹密码
     * @param isChecked
     * @param isChange  是否是修改手势密码
     */
    private void showInputDialog(final int type, final boolean isChecked, final boolean isChange) {
        final IcbcDialog dialog = new IcbcDialog(this);
        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("输入密码");
        dialog.setEditTextType(true);
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
//                applyPwd("", type, isChecked, isChange);
                failChange(type, isChecked, isChange);
                dialog.dismiss();
            }
        });
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                passwordStr = dialog.getEditTextContent();
                if (TextUtils.isEmpty(passwordStr)) {
                    showToast("请输入密码");
                    return;
                }
                String rsaKey = getRsaKey();
                String pwdEncode = "";
                if (!TextUtils.isEmpty(rsaKey)) {
                    pwdEncode = RSACryptographyUtil.encryptByPublicKey(passwordStr, rsaKey);
                }
                applyPwd(pwdEncode, type, isChecked, isChange);
            }
        }).show();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                dialog.showKeyboard();
            }
        }, 200);
    }

//    /**
//     * 验证密码
//     *
//     * @param type
//     * @param isChecked
//     * @param pwd
//     */
//    private void checkPwd(int type, boolean isChecked, String pwd, boolean isChange, boolean isFromCancel) {
//        if (!"111aaa".equals(pwd)) {
//            if (!isChange) {
//                switch (type) {
//                    case 1:
//                        isGestureChanged = false;
//                        if (isChecked) {
//                            sbGesturePwd.setChecked(false);
//                        } else {
//                            sbGesturePwd.setChecked(true);
//                        }
//                        break;
//                    case 2:
//                        isFingerPrintChanged = false;
//                        if (isChecked) {
//                            sbFingerPrintPwd.setChecked(false);
//                        } else {
//                            sbFingerPrintPwd.setChecked(true);
//                        }
//                        break;
//                    default:
//                        break;
//                }
//            }
//            return;
//        }
//        if (isChange) {
//            Intent intent = new Intent();
//            intent.setClass(mActivity, SetGestureStep1Activity.class);
//            intent.putExtra(MentorConst.GET_PASSWORD, pwd);
//            intent.putExtra(MentorConst.IS_CHANGE_GESTURE_PWD, true);
//            startActivity(intent);
//        } else {
//            changeChecked(type, isChecked, pwd);
//        }
//    }

    /**
     * 申请手势或指纹密码
     *
     * @param tradePassword
     * @param type          1--手势密码，2--指纹密码
     * @param isChecked
     * @param isChange      是否是修改手势密码
     */
    private void applyPwd(final String tradePassword, final int type, final boolean isChecked,
                          final boolean isChange) {
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        params.put("tradePassword", tradePassword);
        switch (type) {
            case 1:
                params.put("loginState", "2");
                break;
            case 2:
                params.put("loginState", "1");
                break;
            default:
                break;
        }
        params.put("mobileStyle", Build.MANUFACTURER);

        Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.OPEN_SIGN_FINGER_PRINT_CAPPLY, params));
        OkGo.<String>post(HostConstant.OPEN_SIGN_FINGER_PRINT_CAPPLY)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new com.lzy.okgo.callback.StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateApply(response.body(), type, isChecked, isChange, tradePassword);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        failChange(type, isChecked, isChange);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateApply(String json, int type, boolean isChecked,
                             boolean isChange, String tradePassword) {
        OpenSignFingerprintApplyBean bean;
        try {
            bean = new Gson().fromJson(json, OpenSignFingerprintApplyBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            failChange(type, isChecked, isChange);
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            failChange(type, isChecked, isChange);
            return;
        }

        if (isChange) {
            Intent intent = new Intent();
            intent.setClass(mActivity, SetGestureStep1Activity.class);
            intent.putExtra(MentorConst.GET_PASSWORD, passwordStr);
            intent.putExtra(MentorConst.IS_SHOW_SKIP, false);
            intent.putExtra(MentorConst.IS_CHANGE_GESTURE_PWD, true);
            startActivity(intent);
        } else {
            changeChecked(type, isChecked, passwordStr);
        }

    }

    private void failChange(int type, boolean isChecked, boolean isChange) {
        if (!isChange) {
            switch (type) {
                case 1:
                    isGestureChanged = false;
                    if (isChecked) {
                        sbGesturePwd.setChecked(false);
                    } else {
                        sbGesturePwd.setChecked(true);
                    }
                    break;
                case 2:
                    isFingerPrintChanged = false;
                    if (isChecked) {
                        sbFingerPrintPwd.setChecked(false);
                    } else {
                        sbFingerPrintPwd.setChecked(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 改变状态
     *
     * @param type
     * @param isChecked
     */
    private void changeChecked(int type, final boolean isChecked, String pwd) {
        switch (type) {
            case 1:
                if (isChecked) {
                    Intent intent = new Intent();
                    intent.setClass(mActivity, SetGestureStep1Activity.class);
                    intent.putExtra(MentorConst.IS_SHOW_SKIP, false);
                    intent.putExtra(MentorConst.GET_PASSWORD, pwd);
                    intent.putExtra(MentorConst.IS_CHANGE_GESTURE_PWD, false);
                    startActivity(intent);
                } else {
                    deleteSecretKey(mActivity, PreferencesUtils.getString(this, MentorConst.LAST_LOGIN_USER_ID, ""), 1);
                    rlChangeGesturePwd.setVisibility(View.GONE);
                }
                break;
            case 2:

                if (isChecked) {
                    initFingerPrint(pwd, isChecked);

                    fingerPrintDialog = new IcbcDialog(this);
                    fingerPrintDialog.setAnimationEnable(true);
                    fingerPrintDialog.setCancelable(false);
                    fingerPrintDialog.setTitle("指纹验证");
                    fingerPrintDialog.setContentText("请设置XXXXXX登录指纹");
                    fingerPrintDialog.setContentImage(getResources().getDrawable(R.mipmap.finger_red));
                    fingerPrintDialog.setPositiveListener("取消", new IcbcDialog.OnPositiveListener() {
                        @Override
                        public void onClick(IcbcDialog dialog) {
                            dialog.dismiss();

//                            isFingerPrintChanged = false;
//                            if (isChecked) {
//                                sbFingerPrintPwd.setChecked(false);
//                            } else {
//                                sbFingerPrintPwd.setChecked(true);
//                            }

                            if (signal != null) {
                                signal.cancel();
                                signal = null;
                            }
                        }
                    }).show();
                }

                break;
            default:
                break;
        }
    }

    private void initFingerPrint(String pwd, boolean isChecked) {
        initFinger();
        if (isFingerprint()) {
            startListen(pwd, isChecked);
        }
    }

    /**
     * 获得系统服务对象的引用
     */
    private void initFinger() {
        //通过V4包获得对象
        manager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
        keyManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        signal = new CancellationSignal();

    }

    @TargetApi(Build.VERSION_CODES.M)
    private boolean isFingerprint() {
        //此方法为了保证判断是否支持支持指纹不报错
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getBaseContext(), "没有指纹解锁的权限", Toast.LENGTH_SHORT).show();
            return false;
        }
        //硬件设备是否支持指纹解锁功能
        if (!manager.isHardwareDetected()) {
            Toast.makeText(getBaseContext(), "该手机不支持指纹解锁", Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否有锁屏密码
        if (!keyManager.isKeyguardSecure()) {
            Toast.makeText(getBaseContext(), "请设置锁屏密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        //判断是否录入指纹
        if (!manager.hasEnrolledFingerprints()) {
            Toast.makeText(getBaseContext(), "没有录入指纹", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 开始指纹识别
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void startListen(final String pwd, final boolean isChecked) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getBaseContext(), "没有指纹解锁的权限", Toast.LENGTH_SHORT).show();
            return;
        }

        FingerprintManager.AuthenticationCallback callBack = new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
//                Toast.makeText(getBaseContext(), "操作过于频繁,请稍后再试" + errString, Toast.LENGTH_SHORT).show();
                Logger.t("onAuthenticationError").d(errString.toString());

                fingerPrintDialog.dismiss();
                IcbcDialog dialog = new IcbcDialog(mActivity);
                dialog.setAnimationEnable(true);
                dialog.setCancelable(false);
                dialog.setTitle("指纹验证");
                dialog.setContentText(errString.toString());
                dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
                    @Override
                    public void onClick(IcbcDialog dialog) {
                        dialog.dismiss();

                        if (isChecked) {
                            isFingerPrintChanged = false;
                            sbFingerPrintPwd.setChecked(false);
                        } else {
                            sbFingerPrintPwd.setChecked(true);
                        }

                        if (signal != null) {
                            signal.cancel();
                            signal = null;
                        }
                    }
                }).show();
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                super.onAuthenticationHelp(helpCode, helpString);
                Logger.t("onAuthenticationHelp").d(helpString.toString());
            }

            //指纹识别成功
            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                Logger.t("onAuthenticationSucceeded").d(result.toString());

//                fingerErrorNum = 0;

                if (isChecked) {
                    if (TextUtils.isEmpty(pwd)) {
                        showToast("缺少密码参数~");
                        return;
                    }

                    internetOpen(pwd, isChecked);
                } else {
                    clearFingerPrint(mentorApplication.userBean.getUserId());
                }

                fingerPrintDialog.dismiss();
            }

            //指纹识别失败
            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
                Toast.makeText(getBaseContext(), "指纹设置失败", Toast.LENGTH_SHORT).show();
//                fingerErrorNum++;
//
//                if (fingerErrorNum == ERROR_TIEMS) {
//                    fingerErrorNum = 0;
//
//                    fingerPrintDialog.dismiss();
//
//                    IcbcDialog dialog = new IcbcDialog(mActivity);
//                    dialog.setAnimationEnable(true);
//                    dialog.setCancelable(false);
//                    dialog.setTitle("指纹验证");
//                    if (isChecked) {
//                        dialog.setContentText("指纹设置失败");
//                    } else {
//                        dialog.setContentText("指纹取消失败");
//                    }
//                    dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
//                        @Override
//                        public void onClick(IcbcDialog dialog) {
//                            dialog.dismiss();
//
////                            isFingerPrintChanged = false;
////                            if (isChecked) {
////                                sbFingerPrintPwd.setChecked(false);
////                            } else {
////                                sbFingerPrintPwd.setChecked(true);
////                            }
//
//                            if (signal != null) {
//                                signal.cancel();
//                                signal = null;
//                            }
//                        }
//                    });
//
//                    dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
//                        @Override
//                        public void onClick(IcbcDialog dialog) {
//                            dialog.dismiss();
//
////                            isFingerPrintChanged = false;
////                            if (isChecked) {
////                                sbFingerPrintPwd.setChecked(false);
////                            } else {
////                                sbFingerPrintPwd.setChecked(true);
////                            }
//
//                            if (signal != null) {
//                                signal.cancel();
//                                signal = null;
//                            }
//                        }
//                    }).show();
//                }
            }
        };
        manager.authenticate(cryptoObject, signal, 0, callBack, null);

    }

    private void internetOpen(String pwd, final boolean isChecked) {
        Map<String, String> params = new HashMap<>();
        params.put("identityNo", mentorApplication.userBean.getUserId());
        params.put("tradePassword", pwd);
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());
        params.put("loginState", "1");//开启或者修改的内容 	1指纹  2手势
        params.put("fingerprintKey", getLocalSecretKey(mActivity, mentorApplication.userBean.getUserId()));
        params.put("signKey", "");
        String randomKey = "";
        for (int i = 0; i < 6; i++) {
            randomKey += String.valueOf((int) (Math.random() * 10));
        }
        final String randomFKey = HttpUtils.getMD5(getUUID() + randomKey);
        params.put("randomKey", randomFKey);
        params.put("mobileStyle", Build.MANUFACTURER);

        Logger.t("-----BASE_URL-----").d(HttpUtils.createRequestUrl(this, HostConstant.OPEN_SIGN_FINGER_PRINT_CONFIRM, params));
        OkGo.<String>post(HostConstant.OPEN_SIGN_FINGER_PRINT_CONFIRM)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        updateInternetOpen(response.body(), randomFKey, isChecked);
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void updateInternetOpen(String json, String randomFKey, final boolean isChecked) {
        OpenSignFingerprintConfirmBean bean;
        try {
            bean = new Gson().fromJson(json, OpenSignFingerprintConfirmBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            if (isChecked) {
                isFingerPrintChanged = false;
                sbFingerPrintPwd.setChecked(false);
            } else {
                sbFingerPrintPwd.setChecked(true);
            }
            if (signal != null) {
                signal.cancel();
                signal = null;
            }
            return;
        }

        mentorApplication.userBean.setIsFingerPrintOpen(true);
        updateFingerPrint(mentorApplication.userBean, randomFKey);
    }

    private static final int REQUEST_CHANGE_PWD = 987;

    @OnClick({R.id.leftButton, R.id.rl_change_pwd, R.id.rl_change_gesture_pwd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.rl_change_pwd:
                Intent intent = new Intent(this, EditUserPwdActivity.class);
                startActivityForResult(intent, REQUEST_CHANGE_PWD);
                break;
            case R.id.rl_change_gesture_pwd:
                showInputDialog(1, true, true);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGestureSetCallBack(GestureEvent event) {
        //System.out.println(1);
        if (event.isSuccess) {
            //System.out.println(2);
            rlChangeGesturePwd.setVisibility(View.VISIBLE);
            sbGesturePwd.setChecked(true);
            PreferencesUtils.putBoolean(this, findUserId() + "CanGesture", true);
        } else {
            isGestureChanged = false;
            //System.out.println(3);
            sbGesturePwd.setChecked(false);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //修改密码和上传身份证照片回来后重新检查页面的状态
        if (requestCode == REQUEST_CHANGE_PWD && resultCode == RESULT_OK) {
            CheckViewState();
        }
    }

    private void CheckViewState() {
        if ((Double.parseDouble(minSdkVersion) >= 23 &&
                PreferencesUtils.getString(this, MentorConst.MOBILE_WHITE).contains(Build.MANUFACTURER))) {
            rlFingerPrint.setVisibility(View.VISIBLE);
        }

        if (getGestureOpen(mentorApplication.userBean.getUserId())) {
            rlChangeGesturePwd.setVisibility(View.VISIBLE);
            sbGesturePwd.setChecked(true);
        } else {
            sbGesturePwd.setChecked(false);
            rlChangeGesturePwd.setVisibility(View.GONE);
        }

        if (getFingerPrintOpen(mentorApplication.userBean.getUserId())) {
            sbFingerPrintPwd.setChecked(true);
        } else {
            sbFingerPrintPwd.setChecked(false);
        }
    }


    private void isRecordIdentNumber(final int type, final boolean isChecked) {
        UserBean bean = findUser(getLoginUserId());
        if (bean == null) {
            return;
        }
        if ("1".equals(bean.getRecordIdentNumber())) {//记录了证件号码

            if (type == 1) {
                setGesturePwd(isChecked);
            }
            if (type == 2) {
                setFingerPrintPwd(isChecked);
            }
//            if (isFingerPrintChanged) {
//                showInputDialog(2, isChecked, false);
//            } else {
//                isFingerPrintChanged = true;
//            }
            return;
        }

        IcbcDialog dialog = new IcbcDialog(this);

        dialog.setAnimationEnable(true);
        dialog.setCancelable(false);
        dialog.setTitle("提示");
        dialog.setContentText("如果设置了手势或指纹密码，则会默认记住证件号码。");
        dialog.setEditTextType(false);
        dialog.setNegativeListener("取消", new IcbcDialog.OnNegativeListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();
                if (type == 1) {
                    sbGesturePwd.setChecked(false);
                }
                if (type == 2) {
                    sbFingerPrintPwd.setChecked(false);
                }
            }
        });
        dialog.setPositiveListener("确定", new IcbcDialog.OnPositiveListener() {
            @Override
            public void onClick(IcbcDialog dialog) {
                dialog.dismiss();

                if (type == 1) {
                    setGesturePwd(isChecked);
                }
                if (type == 2) {
                    setFingerPrintPwd(isChecked);
                }
            }
        }).show();
    }

    private void setGesturePwd(boolean isChecked) {
        if (isGestureChanged) {
            showInputDialog(1, isChecked, false);
        } else {
            isGestureChanged = true;
        }
    }

    private void setFingerPrintPwd(boolean isChecked) {

        if (isFingerPrintChanged) {
            showInputDialog(2, isChecked, false);
        } else {
            isFingerPrintChanged = true;
        }
    }
}
